package chat.user.servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import chat.user.domain.Info;
import chat.user.domain.User;
import chat.user.service.InfoService;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class InfoServlet
 */
@WebServlet("/InfoServlet")
public class InfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	InfoService infoService = new InfoService();
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		
		List<Info> infoList = infoService.selectInfo();
		
		JSONArray ja = JSONArray.fromObject(infoList);
		
		response.getWriter().println(ja.toString());
		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		
		String content = request.getParameter("content");
		if(content == "")
		{
			return;
		}
		
		Info info = new Info();
		
		User session_user = (User)request.getSession().getAttribute("session_user");
		info.setUser(session_user);
		
		
		info.setContent(content);
		
		Date date = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		String sendtime = df.format(date);
		info.setSendtime(sendtime);
		
		String ip = request.getRemoteAddr();
		info.setIp(ip);
		
		infoService.addInfo(info);
		
	}
}
